package com.angis.fx.activity.service;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;

import com.angis.fx.activity.Enforcement;
import com.angis.fx.util.GeoLatLng;

public class GPSService extends Service {
	
	private LocationManager locMan;
	
	private GPSBinder mBinder = new GPSBinder();
	
	private double mLat;
	
	private double mLon;
	

	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	@Override
	public void onCreate() {
		openGPS();
	}
	
	public GeoLatLng getGeoLatLon(){
		return new GeoLatLng(mLat, mLon);
	}
	
	public void returnGeoLatLon(){
		Intent intent = new Intent("sendgps");
		intent.putExtra("geolatlon", new GeoLatLng(mLat, mLon));
		this.sendBroadcast(intent);
	}
	
	private void openGPS() {
		try {
			locMan = (LocationManager) getSystemService(LOCATION_SERVICE);

			// 注册位置移动监听器
			locMan.requestLocationUpdates("gps", Enforcement.GPSSecond, 5, locationListener);
//			Location lLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//			mLat = lLoc.getLatitude();
//			mLon = lLoc.getLongitude();
			returnGeoLatLon();
			Toast.makeText(this, "GPS服务已经启动", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Toast.makeText(this, "打开GPS报错", Toast.LENGTH_SHORT).show();
		}
	}
	
	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location location) { // 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
			// log it when the location changes
			if (location != null) {
				mLat = location.getLatitude();
				mLon = location.getLongitude();
				returnGeoLatLon();
//				Toast.makeText(GPSService.this, "纬度："+mLat+";经度："+mLon, Toast.LENGTH_LONG).show();
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
	};

	@Override
	public void onDestroy() {
		locMan.removeUpdates(locationListener);
		Toast.makeText(this, "GPS服务已停止", Toast.LENGTH_SHORT).show();
		super.onDestroy();
	}
	
	public class GPSBinder extends Binder{
		GPSService getService(){
			return GPSService.this;
		}
	}

}

